package com.li.net;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Iterator;

public class ServerSocketChannelDemo {
	public static void main(String[] args) throws Exception {
		testServerSocketChannel();
	}
	
	public static void testServerSocketChannel() throws Exception{
		//1、打开一个serversocket通道，并绑定到相应的端口中
		ServerSocketChannel serverChannel=ServerSocketChannel.open();
		InetSocketAddress inetSocketAddress=new InetSocketAddress(8888);
		serverChannel.bind(inetSocketAddress);
		//2、监听一个指定的端口
		SocketChannel inChannel=serverChannel.accept();
		//3、分配一个缓冲
		ByteBuffer byteBuffer=ByteBuffer.allocate(10);
		
		FileChannel outChannel=FileChannel.open(Paths.get("src/main/java/com/li/net/2.txt"), StandardOpenOption.READ,StandardOpenOption.WRITE,StandardOpenOption.CREATE);
		//4、从远程的主机读取数据到服务器本地中
		while(inChannel.read(byteBuffer)!=-1){
			byteBuffer.flip();
			outChannel.write(byteBuffer);
			System.out.print(new String(byteBuffer.array()));
			byteBuffer.clear();
		}
		//5、关闭通道
		outChannel.close();
		inChannel.close();
	}
	
	public static void testNonBlockingServerSocketChannel() throws Exception {
		ServerSocketChannel serverSocketChannel=ServerSocketChannel.open();
		serverSocketChannel.configureBlocking(false);
		InetSocketAddress inetSocketAddress=new InetSocketAddress(8888);
		serverSocketChannel.bind(inetSocketAddress);
		
		Selector selector=Selector.open();
		serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
		
		while(selector.select()>0){
			Iterator<SelectionKey> it=selector.selectedKeys().iterator();
			while(it.hasNext()){
				SelectionKey selectionKey=it.next();
				if(selectionKey.isAcceptable()){
					SocketChannel socketChannel=serverSocketChannel.accept();
					socketChannel.configureBlocking(false);
					socketChannel.register(selector, SelectionKey.OP_READ);
				}else if(selectionKey.isReadable()){
					SocketChannel inChannel=(SocketChannel) selectionKey.channel();
					ByteBuffer byteBuffer=ByteBuffer.allocate(10);
					
					while(inChannel.read(byteBuffer)>0){
						byteBuffer.flip();
						System.out.print(new String(byteBuffer.array()));
						byteBuffer.clear();
					}
				}
				it.remove();
			}
		}
	}
	
	
}
